package cc.vv.baselibrary.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import cc.vv.BaseNewApplication;
import cc.vv.baselibrary.R;
import cc.vv.baselibrary.bean.base.BaseResponseObj;
import cc.vv.baselibrary.global.BCIntentKey;
import cc.vv.baselibrary.global.UserInfoSharePreKey;
import cc.vv.baselibrary.http.BaseHttpResponseKey;
import cc.vv.baselibrary.http.BaseHttpResponseObj;
import cc.vv.baselibrary.util.ColorUtil;
import cc.vv.baselibrary.util.LKAppUtil;
import cc.vv.baselibrary.util.LKLogUtil;
import cc.vv.baselibrary.util.LKPrefUtil;
import cc.vv.baselibrary.util.router.RouterActivityIntentResourceKey;
import cc.vv.baselibrary.util.router.RouterTransferCenterUtil;
import cc.vv.baselibrary.util.voice.IMVoicePlayer;
import cc.vv.baselibrary.vFinal.BTCodeKey;
import cc.vv.baselibrary.vFinal.BTParamKey;
import cc.vv.baselibrary.view.BCSingleButtonDialog;
import cc.vv.baselibrary.view.jzvd.JZVideoPlayerStandard;
import cc.vv.lkbasecomponent.base.ui.LKBaseActivity;
import cc.vv.lklibrary.log.LogOperate;

/**
 * 公共Activity基类
 *
 * @author chen.qi
 */
public class UtimingBaseActivity extends LKBaseActivity {

    protected Context mContext;

    private BaseNewApplication application;

    private BCSingleButtonDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initStatusBarColor();
    }

    @Override
    protected void initView(@Nullable Bundle bundle) {
        mContext = this;
        if (application == null) {
            // 得到Application对象
            application = (BaseNewApplication) getApplication();
        }
        addActivity();
    }

    public void addActivity() {
        if (null != application) {
            application.addActivity(this);
        }
    }

    public void removeActivity() {
        if (null != application) {
            application.removeActivity(this);
        }
    }

    public void removeActivity(Activity activity) {
        if (null != application) {
            application.removeActivity(activity);
        }
    }

    public void exitApp() {
        if (null != application) {
            application.exitApp();
        }
    }

    public void exit(int num) {
        if (null != application) {
            application.exit(num);
        }
    }

    public void finishActivityAndRemove() {
        if (null != application) {
            application.finishActivityAndRemove();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerActionObject();
    }

    private void registerActionObject() {
        try {
            EventBus.getDefault().register(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        closeInput();
    }

    @Override
    protected void onStop() {
        super.onStop();
        getLoading().closeLoading();
        try {
            //解注册
            EventBus.getDefault().removeAllStickyEvents();
            EventBus.getDefault().unregister(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            JZVideoPlayerStandard.releaseAllVideos();
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }

        try {
            IMVoicePlayer.getInstance().stop();
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (null != dialog && dialog.isShowing()) {
                dialog.dismiss();
                dialog = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        removeActivity();

        try {
            IMVoicePlayer.getInstance().stop();
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void onEvent(BaseHttpResponseObj event) {
        setRequestResultData(event);
    }


    @Subscribe(threadMode = ThreadMode.MAIN, priority = 100)
    public void onEvent(String event) {
        if (BTParamKey.OTHER_DEVICE_LOGIN.equals(event)) {
            showDistanceLoginDialog("您的登录信息已过期，请重新登录");
        }
    }

    /**
     * 请求结果数据设置
     */
    private void setRequestResultData(BaseHttpResponseObj event) {
        if (null == event) {
            return;
        }
        if (!isTopOfStack()) {
            return;
        }
        if (BaseHttpResponseKey.RESPONSE_TYPE_START.equals(event.getResponseType())) {
            //请求开始
            if (event.isLoading()) {
                getLoading().showLoading();
            }
        } else if (BaseHttpResponseKey.RESPONSE_TYPE_SUCCESS.equals(event.getResponseType())) {
            //请求成功success
            BaseResponseObj data = event.getData();
            if (null != data) {
                if (data.statusCode == BTCodeKey.CODE_200) {
                    getData(data);
                } else if ("A".equals(data.level)) {
                    getData(data);
                } else {
                    if (data.statusCode == BTCodeKey.CODE_10002) {
                        //token失效
                        showDistanceLoginDialog("您的登录信息已过期，请重新登录");
                    } else if (data.statusCode == BTCodeKey.CODE_10003) {
                        //token失效
                        showDistanceLoginDialog("您的账号已在其他设备登录，请重新登录");
                    } else {
                        getBadCode(data);
                    }
                }
            }
        } else if (BaseHttpResponseKey.RESPONSE_TYPE_FINISH.equals(event.getResponseType())) {
            //请求完成
            getLoading().closeLoading();
        } else if (BaseHttpResponseKey.RESPONSE_TYPE_FAILURE.equals(event.getResponseType())) {
            //请求失败
            getLoading().closeLoading();
            onHttpFailure(event.getUrl(), event.getExceptionStr());
        }
    }


    private void showDistanceLoginDialog(String content) {
        if (null == dialog) {
            try {
                dialog = new BCSingleButtonDialog(this);
                dialog.setTitle("登录过期");
                dialog.setContent(content);
                dialog.setConfirmBtnText("重新登录");
                dialog.setEventInterface(new BCSingleButtonDialog.EventInterface() {
                    @Override
                    public void confirmOnClick() {
                        //跳转登录
                        exitApp();
                        dialog.dismiss();
                        LKPrefUtil.clearSP(UserInfoSharePreKey.USERINFO_DATA, UserInfoSharePreKey.TOKEN,
                                UserInfoSharePreKey.LOGIN_INFO, UserInfoSharePreKey.SESSIONID);
                        Intent intent = RouterTransferCenterUtil.getInstance().getRouterIntent(mContext,
                                RouterActivityIntentResourceKey.KEY_MODULE_LOGIN);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        intent.putExtra(BCIntentKey.OUT_LINE, true);
                        startActivity(intent);
                    }
                });
            } catch (Exception e) {
                LogOperate.e(e.getMessage(), e);
            }
        }
        if (null != dialog && !dialog.isShowing()) {
            dialog.show();
        }
    }


    /**
     * 接口请求成功code值为非200和300时
     */
    protected void getBadCode(BaseResponseObj obj) {

    }

    /**
     * 接口请求成功回调
     */
    protected void getData(BaseResponseObj obj) {

    }

    /**
     * 接口请求失败回调
     */
    protected void onHttpFailure(String url, String exceptionStr) {
        LKLogUtil.e(url + ":" + exceptionStr);
    }

    /**
     * 当前Activity是否存在于栈顶
     */
    protected Boolean isTopOfStack() {
        String topActivityName = getTopActivity(this);
        if (null == topActivityName) {
            return true;
        }
        String thisActivityName = this.getLocalClassName();
//        LKLogUtil.e("TopActivityName:" + topActivityName);
//        LKLogUtil.e("ThisActivityName:" + thisActivityName);
        if (topActivityName.contains(thisActivityName)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获得栈中最顶层的Activity
     *
     * @param context
     * @return
     */
    private String getTopActivity(Context context) {
        android.app.ActivityManager manager = (android.app.ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
        if (runningTaskInfos != null) {
            return (runningTaskInfos.get(0).topActivity).toString();
        } else
            return null;
    }

    /**
     * 隐藏键盘
     */
    public void closeInput() {
        try {
            LKAppUtil.getInstance().closeInput(mContext, getWindow().getDecorView());
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
    }

    /**
     * 初始化状态栏颜色
     */
    private void initStatusBarColor() {
        try {
            //状态栏颜色字体(白底黑字)修改 Android6.0+
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                Window window = getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(ColorUtil.setBCColor(R.color.color_E31E26));
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }
            //状态栏颜色字体(白底黑字)修改 MIUI6+
            setMiuiStatusBarDarkMode(this, true);
            //状态栏颜色字体(白底黑字)修改 Flyme4+
            //setMeizuStatusBarDarkIcon(this,true);
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
            LKLogUtil.e(e.toString(), e);
        }
    }

    /**
     * 状态栏颜色字体(白底黑字)修改 MIUI6+
     *
     * @param activity
     * @param darkmode
     * @return
     */
    private boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 状态栏颜色字体(白底黑字)修改 Flyme4+
     *
     * @param activity
     * @param dark
     * @return
     */
    private boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }
}
